
window.onload = function () {
    scroll();
}

function scroll(){

    var scroll = document.querySelector('.scroll');
    var scrWidth = scroll.offsetWidth;
    var imgBox = scroll.querySelector('ul:first-child');
    var olBox = scroll.querySelector('ol');
    var ollis = olBox.querySelectorAll('li');
    var newUl = scroll.querySelector('ul:last-child');
    var newlis = newUl.querySelectorAll('li');

    /*公用方法*/
    /*加过渡*/
    var addTransition = function(){
        imgBox.style.webkitTransition = 'all 0.3s';/*兼容性*/
        imgBox.style.transition = 'all 0.3s';
    }
    /*清除过渡*/
    var removeTransition = function(){
        imgBox.style.webkitTransition = 'none';
        imgBox.style.transition = 'none';
    };
    /*定位*/
    var setTranslateX = function(translateX){
        imgBox.style.webkitTransform = 'translateX('+translateX+'px)';
        imgBox.style.transform = 'translateX('+translateX+'px)';
    }

    //1.自动轮播 且是无缝
    var index = 1;
    var timer = setInterval(function () {
        index++;
        addTransition();
        setTranslateX(-index*scrWidth);
    },2000)

    yky.transitionEnd(imgBox, function () {
        if(index>=5){
            index = 1;
            removeTransition();
            setTranslateX(-index*scrWidth);
        }else if(index<=0){
            index = 4;
            removeTransition();
            setTranslateX(-index*scrWidth);
        }
        setPoint();
        setNew();
    });

    var setPoint = function () {
        for(var i=0;i<ollis.length;i++){
            ollis[i].classList.remove('curr');
        }
        ollis[index-1].classList.add('curr');
    }
    var setNew = function () {
        for(var i=0;i<newlis.length;i++){
            newlis[i].classList.remove('new');
        }
        newlis[index-1].classList.add('new');
    }
    //3.滑动手指触摸滑动的时候轮播图也能随着滑动
    var stratX = 0;
    var moveX = 0;
    var isMove = false;

    imgBox.addEventListener('touchstart', function (e) {
        stratX = e.touches[0].clientX;
        clearInterval(timer);
    });
    imgBox.addEventListener('touchmove', function (e) {
        moveX = e.touches[0].clientX - stratX;
        removeTransition();
        setTranslateX(-index*scrWidth+moveX);
        isMove = true;
    });
    window.addEventListener('touchend', function (e) {
        if(Math.abs(moveX)>scrWidth/3 && isMove){
            if(moveX>0){
                index--;
            }else {
                index++;
            }
            addTransition();
            setTranslateX(-index*scrWidth);
        }else {
            addTransition();
            setTranslateX(-index*scrWidth);
        }

        stratX = 0;
        moveX = 0;
        isMove = false;

        clearInterval(timer);
        timer = setInterval(function () {
            index++;
            addTransition();
            setTranslateX(-index*scrWidth);
        },2000)
    });


}